package com.leave.controller;

import java.io.IOException;
import java.util.List;
import java.util.zip.ZipInputStream;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.leave.util.DateUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class ProcessDeployController {

	//注入activitiService服务
	@Autowired
	private RepositoryService repositoryService;
	
	
	@RequestMapping("/getAllProcessByPage")
	@ResponseBody
	public String getAllProcessByPage(Integer page,Integer rows) {
		
//		Long processDefinitionCount = repositoryService.createProcessDefinitionQuery().count();
//		
//		List<ProcessDefinition> pdList = repositoryService.createProcessDefinitionQuery()
//															.list();
		
		//获取流程定义的总数量
		Long deploymentCount = repositoryService.createDeploymentQuery().count();
		//获取流程集合
		List<Deployment> dpList = repositoryService.createDeploymentQuery()
									.orderByDeploymenTime().desc()
									.listPage((page-1)*rows, rows);
		
		JSONArray jsArr = new JSONArray();
		for(int i = 0;i<dpList.size();i++) {
			JSONObject js=new JSONObject();
			js.put("id", dpList.get(i).getId());
			js.put("name", dpList.get(i).getName());
			js.put("time", DateUtil.formatDate(dpList.get(i).getDeploymentTime(), "yyyy-MM-dd HH:mm"));
			js.put("category", dpList.get(i).getCategory());
			js.put("tenantId", dpList.get(i).getTenantId());
			jsArr.add(js);
		}
		JSONObject js=new JSONObject();
		js.put("rows", jsArr);
		js.put("total", deploymentCount);		
		
		return js.toString();
	}
	
	
	
	@RequestMapping("/uploadProcess")
	@ResponseBody
	public String uploadProcess(MultipartFile file) throws IOException {
		ZipInputStream zip = new ZipInputStream(file.getInputStream());
		String fileName = file.getOriginalFilename();
		repositoryService.createDeployment().name(fileName).addZipInputStream(zip).deploy();
		
		return "success";
	}
	
	
	@RequestMapping("/removeProcessByArrId")
	@ResponseBody
	public String removeProcessByArrId(int[] arrId) {
		for(int i : arrId) {
			repositoryService.deleteDeployment(i+"",true);
		}
		return "success";
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
